﻿
using System;
using System.ServiceModel;

using WSU.Cheka.HelloWCF.Contracts;
using WSU.Cheka.HelloWCF.Services;

namespace WSU.Cheka.HelloWCF.Host
{
    static class SingleEndpointHost
    {
        /// <summary>
        /// host the service by hardcoding the configurations in the source codes
        /// !!!!!!! PAY ATTENTION: since the constructor ServiceHost will always load configuration from XML first
        /// so after we provide XML configuration, using "AddServiceEndpoint" to add the same endpoint will throw exception
        /// </summary>
        private static void ManualHost()
        {
            // relationship between host and service instance is 1 : 1
            // one servicehost corresponds to one service instance
            using (ServiceHost host = new ServiceHost(typeof(HelloWcfService)))
            {
                // the different interface of the same service instance can be bound to different to different address
                // and by different transmission protocol
                host.AddServiceEndpoint(typeof(IHelloWCF), new NetTcpBinding(), "net.tcp://localhost:9000/HelloWCF");
                host.Opened += (sender, evtargs) => { Console.WriteLine("manual service has been started."); };

                host.Open();// it will not block the whole application

                Console.WriteLine("Press any key to exit the service, ......");
                Console.ReadLine();
            }
        }

        /// <summary>
        /// from the codes, we can see that "Manual Service Host" and "Host By Config"
        /// have no big differences
        /// even if your host is XML configured, you can still use "AddServiceEndpoint" to manually add Endpoint
        /// that doesn't appear in the XML file
        /// </summary>
        private static void HostByConfig()
        {
            // the class name of the service must match the name property of the <service> element in the XML configuration
            using (ServiceHost host = new ServiceHost(typeof(HelloWcfService)))
            {
                host.Opened += (sender, evtargs) => { Console.WriteLine("service by config has been started."); };
                host.Open();
                Console.WriteLine("Press any key to exit the service, ......");
                Console.ReadLine();
            }
        }

        public static void TestMain()
        {
            // ManualHost();
            HostByConfig();
        }
    }
}
